package utils;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.opencv.core.Core;
import org.opencv.core.Point;
import org.opencv.core.Scalar;

@SuppressWarnings("serial")
public class View extends JFrame {

	JLabel label = new JLabel();
	JPanel imagePanel = new JPanel();
	MatToImage mti = new MatToImage();
	DateHandler dh = new DateHandler();
	int sum = 0, cont = 0, interno = 0;
	double time = 0;

	public View(final ImageDeted id) {

		imagePanel.add(label);

		this.setSize(640, 480);
		this.add(imagePanel);
		this.setVisible(true);

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		dh.restart();

		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				id.switchOff();
			}
		});
	}

	public void update(ImageDeted id) {

		Core.putText(id.getImage(), "FD: " + id.getNvolti(), new Point(20, 20),
				2, 0.5, new Scalar(0, 0, 0));
		Core.putText(id.getImage(), "Occhi:" + id.getNocchi(),
				new Point(20, 50), 2, 0.5, new Scalar(0, 0, 0));

		Core.putText(id.getImage(), "FRate:" + 1000 / dh.nowEnd() + "fps",
				new Point(20, 80), 2, 0.5, new Scalar(0, 0, 0));
		Core.putText(id.getImage(), "Blinks: " + id.blinks, new Point(20, 110),
				2, 0.5, new Scalar(0, 0, 0));

		if (id.closed > 499)
			Core.putText(id.getImage(), "Last blink:" + id.closed + "ms",
					new Point(20, 140), 2, 0.5, new Scalar(0, 0, 255));
		else
			Core.putText(id.getImage(), "Last blink:" + id.closed + "ms",
					new Point(20, 140), 2, 0.5, new Scalar(0, 0, 0));

		if ((time < 1000 / dh.nowEnd()) && (id.getFace() != null) && (1000/dh.nowEnd() < 80))
			time = (1000 / dh.nowEnd());
		Core.putText(id.getImage(), "Max FPS: " + time, new Point(20, 170), 2,
				0.5, new Scalar(0, 0, 0));
	
		label.setIcon(new ImageIcon(mti.toBufferedImage(id.getImage())));
		
		

		dh.restart();

	}

}
